﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.LinqBuilder;
using Microsoft.EntityFrameworkCore;
using Queer.Entity;
using Queer.IService.OrganizationManage;
using Queer.Model.Param.OrganizationManage;
using Queer.Util;
using Queer.Util.Helper;
using Queer.Util.Model;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace Queer.Service.OrganizationManage
{
    /// <summary>
    /// 创 建：song
    /// 日 期：2020-12-06 14:12
    /// 描 述：部门信息服务类
    /// </summary>

    public class DepartmentService : IDepartmentService, ITransient
    {
        private readonly IRepository<DepartmentEntity> _departmentDB;
        private readonly IRepository<UserEntity> _userDB;

        public DepartmentService(IRepository<DepartmentEntity> departmentDB, IRepository<UserEntity> userDB)
        {
            _departmentDB = departmentDB;
            _userDB = userDB;
        }

        #region 获取数据

        /// <summary>
        /// 带条件查询所有
        /// </summary>
        public async Task<List<DepartmentEntity>> GetList(DepartmentListParam param)
        {
            var data = await ListFilter(param).ToListAsync();
            return data;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<List<DepartmentEntity>> GetPageList(DepartmentListParam param, Pagination pagination)
        {
            var data = await ListFilter(param)
                .OrderByDescending(a => a.Id)
                .ToPagedListAsync(pagination.PageIndex, pagination.PageSize);

            // 分页参数赋值
            pagination.TotalCount = data.TotalCount;
            return data.Items.ToList();
        }

        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        public async Task<DepartmentEntity> GetEntity(long id)
        {
            var list = await _departmentDB.AsQueryable(p => p.Id == id).ToListAsync();
            return list.FirstOrDefault();
        }

        /// <summary>
        /// 查询多个ID主键数据
        /// </summary>
        public async Task<List<DepartmentEntity>> GetListByIds(string ids)
        {
            if (ids.IsNullOrEmpty())
                throw new BusinessException("参数不合法！");

            var idArr = TextHelper.SplitToArray<long>(ids, ',').ToList();
            var data = await _departmentDB.AsQueryable(a => idArr.Contains(a.Id.GetValueOrDefault())).ToListAsync();

            return data;
        }

        #endregion

        #region 提交数据

        public async Task SaveForm(DepartmentEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                await _departmentDB.InsertNowAsync(entity);
            }
            else
            {
                await _departmentDB.UpdateNowAsync(entity, ignoreNullValues: true);
            }
        }

        public async Task DeleteForm(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids))
                throw new BusinessException("参数不合法！");

            var _ids = ids.Split(",");
            await _departmentDB.BatchFakeDeleteAsync(_ids);
        }

        #endregion

        #region 私有方法

        private IQueryable<DepartmentEntity> ListFilter(DepartmentListParam param)
        {
            IQueryable<DepartmentEntity> query = _departmentDB.AsQueryable(a => a.IsDelete != true);

            if (param != null)
            {
                // 部门名称
                if (!string.IsNullOrEmpty(param.DepartmentName))
                    query = query.Where(p => p.DepartmentName.Contains(param.DepartmentName));
            }

            query = from a in query
                    join b in _userDB.AsQueryable(false) on a.PrincipalId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in _userDB.AsQueryable(false) on a.CreateUserId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select new DepartmentEntity()
                    {
                        Id = a.Id,
                        IsDelete = a.IsDelete,
                        CreateTime = a.CreateTime,
                        CreateUserId = a.CreateUserId,
                        DepartmentName = a.DepartmentName,
                        DepartmentCode = a.DepartmentCode,
                        DepartmentSort = a.DepartmentSort,
                        Email = a.Email,
                        Enable = a.Enable,
                        Fax = a.Fax,
                        LastModifyTime = a.LastModifyTime,
                        LastModifyUserId = a.LastModifyUserId,
                        ParentId = a.ParentId,
                        PrincipalId = a.PrincipalId,
                        PrincipalName = b != null ? b.RealName : null,
                        PrincipalPhone = a.PrincipalPhone,
                        Remark = a.Remark,
                        Telephone = a.Telephone,
                        CreateUserName = c != null ? c.RealName : null
                    };

            return query;
        }

        #endregion
    }
}
